<?php 
namespace jm\wechat\common;  
class WeChatCommon
{ 
 	private $key = 'x';   

 
      //私有化构造函数，防止外界实例化对象
  public function __construct($key)
  {
    $this->key=$key;
  }
 
 
    
    /*
     *
     * 产生随机字符串，不长于32位
     * @param int $length
     * @return 产生的随机字符串
     */
    public function getNonceStr($length = 32)
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
 
    /*
     * 生成签名
     * @return 签名
     */
    public function makeSign($data)
    {
        //获取微信支付秘钥
        $key =  $this->key ;
    
        // $key =Config::get("site.wechat_pay_key");
        // 去空
        $data = array_filter($data);
        //签名步骤一：按字典序排序参数
        ksort($data);
        $string_a = http_build_query($data);
        $string_a = urldecode($string_a);
        //签名步骤二：在string后加入KEY
        //$config=$this->config;
        $string_sign_temp = $string_a . "&key=" . $key;
        //签名步骤三：MD5加密
        $sign = md5($string_sign_temp);
        // 签名步骤四：所有字符转为大写
        $result = strtoupper($sign);
        return $result;
    }
 	
 	 //将一个数组转换为 XML 结构的字符串
 
    public function array2xml($arr, $level = 1)
    {
        $s = $level == 1 ? "<xml>" : "";
        foreach ($arr as $tagname => $value) {
            if (is_numeric($tagname)) {
                $tagname = $value['TagName'];
                unset($value["TagName"]);
            }
            if (!is_array($value)) {
                $s .= "<{$tagname}>" . (!is_numeric($value) ? '<![CDATA[' : "") . $value . (!is_numeric($value) ? ']]>' : "") . "</{$tagname}>";
            } else {
                $s .= "<{$tagname}>" . $this->array2xml($value, $level + 1) . "</{$tagname}>";
            }
        }
        $s = preg_replace("/([\x01-\x08\x0b-\x0c\x0e-\x1f])+/", ' ', $s);
        return $level == 1 ? $s . "</xml>" : $s;
    }
 
    /*
     * 将xml转为array
     * @param  string $xml xml字符串
     * @return array    转换得到的数组
     */
    public function xml2array($xml)
    {
      
        libxml_disable_entity_loader(true);
        $result = json_decode(json_encode(simplexml_load_string($xml, "SimpleXMLElement", LIBXML_NOCDATA)), true);
        return $result;
    }
 
} 
 
